<template>
    <div class="drawerContainer" v-loading="loading">
        <div class="chartRoom" ref="scrollContainer">
            <div class="messageInfo" v-if="messageList.length > 0">
                <div v-for="item in messageList">
                    <div style="display:flex;justify-content:flex-start" v-if="item.name == 'report'">
                        <img src="../assets/svg/report.svg" class="reportSvgIcon" alt="">
                        <div class="msgItem">
                            {{ item.msg }}
                        </div>
                    </div>
                    <div style="display:flex;justify-content:flex-end" v-else>
                        <div class="msgItem">
                            {{ item.msg }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="zhilutong" v-else>
                <div style="display: flex;align-items: center;">
                    <img src="../assets/svg/report.svg" class="reportSvg" alt="">
                    <div style="color: rgb(135, 178, 255);font-size: 26px;font-weight: 500;">智路通</div>
                </div>
                <h4>嗨！我是智路通小助手</h4>
                <div class="text1">依托于deepseek智能引擎，结合深厚的公路基础知识库，为公路数字化提供智能检索决策支持</div>
            </div>
        </div>
        <div class="textarea">
            <el-input v-model="textarea" style="width: 100%" :autosize="{ minRows: 4, maxRows: 5 }" type="textarea"
                placeholder="给智路通发送消息" @keydown.enter.prevent="sendMsg" />
            <div class="btnclass">
                <el-button size="small" plain type="info" @click="clear">清空</el-button>
                <el-button size="small" plain type="primary" @click="sendMsg">发送</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import axios from 'axios'
import { onMounted, ref, watch, nextTick } from "vue";
import { generalRequestGet, generalRequestPost } from "@/api/homepage.js";
import { ElMessage, ElMessageBox } from "element-plus";

let messageList = ref([
    // {
    //     name: 'user',
    //     msg: '公路技师学院听起来很酷啊！不过这个学校不是特别出名，所以我可能没有具体的信息。 告诉我你的需求，我就能更好地帮助你哦！'
    // },
])
let textarea = ref('')
let loading = ref(false)
let scrollContainer = ref(null);
onMounted(() => {
    if (scrollContainer.value) {
        scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    }
})


const clear = () => {
    textarea.value = ''
}
const sendMsg = () => {
    if (textarea.value) {
        loading.value = true
        messageList.value.push({ name: 'user', msg: textarea.value })
        let params = { question: textarea.value }
        // fetch(import.meta.env.VITE_API_BASE_URL + '/ai/ai/chat_in_stream?question=' + textarea.value).then(response => {
        fetch('http://10.7.50.18:9001/ai/chat_in_stream?question=' + textarea.value).then(response => {
            // fetch('http://192.168.10.125:9000/ai/chat_in_stream?question=' + textarea.value).then(response => {
            console.log(response, 'response')
            loading.value = false
            textarea.value = ''
            messageList.value.push({ name: 'report', msg: '' })
            const reader = response.body.getReader();
            reader.read().then(function processText({ done, value }) {
                if (done) {
                    return;
                }
                // 将读取到的内容转换为字符串
                let jsonString = new TextDecoder().decode(value)
                let result = [];
                try {
                    const singleObj = JSON.parse(jsonString);
                    result.push(singleObj);
                } catch (error) {
                    const regex = /\{.*?\}/g;
                    const matches = jsonString.match(regex);
                    console.log(matches, 'matches')
                    if (matches) {
                        matches.forEach((match) => {
                            try {
                                const obj = JSON.parse(match);
                                result.push(obj);
                            } catch (parseError) {
                                console.error('解析 JSON 时出错:', parseError);
                            }
                        });
                    }
                }
                let raderDone = result.some(d => {
                    if (d.code != 1000) {
                        ElMessage(d.msg)
                        return true
                    }
                    messageList.value[messageList.value.length - 1].msg = messageList.value[messageList.value.length - 1].msg + d.data.msgContent
                    return false
                })
                if (raderDone) return //如何code ！= 1000，提前结束循环，不再解析
                nextTick(() => {
                    if (scrollContainer.value) {
                        scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
                    }
                })
                return reader.read().then(processText);
            });
        });
    }
}
</script>

<style lang="less" scoped>
.drawerContainer {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .chartRoom {
        flex: 1;
        border-radius: 8px;
        overflow-y: auto;

        .messageInfo {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            padding: 8px;
            font-size: 16px;

            .reportSvgIcon {
                width: 30px;
                height: 30px;
                margin-right: 10px;
            }

            .msgItem {
                margin-bottom: 20px;
                max-width: 450px;
                background-color: rgb(239, 246, 255);
                padding: 5px 10px;
                box-sizing: border-box;
                border-radius: 10px;

            }


        }

        .zhilutong {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 100px;

            .reportSvg {
                width: 60px;
                height: 60px;
                margin-right: 15px;
            }

            .text1 {
                font-size: 10px;
                color: rgb(55, 54, 54);
            }
        }
    }

    .textarea {
        height: 150px;
        box-sizing: border-box;
        border-radius: 5px;
        background-color: #f2f2f2;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding: 0 0 10px 0;
    }

    :deep(.el-textarea__inner) {
        box-shadow: none;
        background-color: #f2f2f2;
    }

    .btnclass {
        box-sizing: border-box;
        padding: 0 10px;
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
}
</style>